// pages/communication/communication.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    posts: [], 
    newPost: '',
    selectedImages: [],
    currentUserName: '',
    commentInputs: {}, // 每个帖子的评论输入内容
    replyInputs: {},   // 每个帖子的回复输入内容
    replyTo: null, // {commentId, userName} 或 null
    replyToPostIndex: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 加载本地存储的帖子
    let posts = wx.getStorageSync('posts') || [];
    // 过滤掉未登录用户发布的帖子
    posts = posts.filter(post => post.user && post.user !== '匿名用户');
    // 同步到本地存储，防止下次再出现
    wx.setStorageSync('posts', posts);
    const userInfo = wx.getStorageSync('userInfo') || { name: '' };
    this.setData({ posts, currentUserName: userInfo.name });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  loadPosts: function() {
  },

  handleInput: function(e) {
    this.setData({ newPost: e.detail.value });
  },
  chooseImage: function() {
    const that = this;
    wx.chooseImage({
      count: 4 - (this.data.selectedImages ? this.data.selectedImages.length : 0), // 剩余可选数量
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        const allImages = (that.data.selectedImages || []).concat(tempFilePaths);
        that.setData({
          selectedImages: allImages.slice(0, 4)
        });
      }
    });
  },

  submitPost: function() {
    const userInfo = wx.getStorageSync('userInfo') || { avatar: '/pages/demo3/imge/gengar.png', name: '' };
    if (!userInfo.name) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    if (this.data.newPost.trim() === '' && (!this.data.selectedImages || this.data.selectedImages.length === 0)) return;
    const newPost = {
      id: Date.now(),
      avatar: userInfo.avatar,
      user: userInfo.name,
      content: this.escapeHTML(this.data.newPost),
      images: this.data.selectedImages && this.data.selectedImages.length > 0 ? this.data.selectedImages : [],
      liked: false
    };
    const posts = [...this.data.posts, newPost];
    this.setData({
      posts,
      newPost: '',
      selectedImages: []
    });
    wx.setStorageSync('posts', posts);
  },

  escapeHTML: function(str) {
    return str.replace(/&/g, '&amp;')
              .replace(/</g, '&lt;')
              .replace(/>/g, '&gt;')
              .replace(/"/g, '&quot;')
              .replace(/'/g, '&#39;');
  },

  previewCommentImage: function(e) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.selectedImages[index],
      urls: this.data.selectedImages
    });
  },

  toggleLike: function(e) {
    const index = e.currentTarget.dataset.index;
    const posts = this.data.posts.slice();
    posts[index].liked = !posts[index].liked;
    this.setData({ posts });
    // 点赞状态也持久化
    wx.setStorageSync('posts', posts);
  },

  deletePost: function(e) {
    const index = e.currentTarget.dataset.index;
    const posts = this.data.posts.slice();
    posts.splice(index, 1);
    this.setData({ posts });
    wx.setStorageSync('posts', posts);
  },

  submitComment: function(e) {
    const userInfo = wx.getStorageSync('userInfo') || { avatar: '', name: '' };
    if (!userInfo.name) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    const postIndex = e.currentTarget.dataset.postIndex;
    const commentContent = this.data.commentInputs[postIndex] || '';
    if (!commentContent.trim()) return;
    const posts = this.data.posts.slice();
    const post = posts[postIndex];
    if (!post.comments) post.comments = [];
    if (this.data.replyTo && this.data.replyToPostIndex === postIndex) {
      // 回复模式
      const comment = post.comments.find(c => c.id === this.data.replyTo.commentId);
      if (comment) {
        if (!comment.replies) comment.replies = [];
        comment.replies.push({
          user: userInfo.name,
          avatar: userInfo.avatar,
          content: commentContent,
          time: new Date().toLocaleString()
        });
      }
    } else {
      // 普通评论
      post.comments.push({
        id: Date.now(),
        user: userInfo.name,
        avatar: userInfo.avatar,
        content: commentContent,
        time: new Date().toLocaleString(),
        replies: []
      });
    }
    this.setData({
      posts,
      [`commentInputs.${postIndex}`]: '',
      replyTo: null,
      replyToPostIndex: null
    });
    wx.setStorageSync('posts', posts);
  },

  handleCommentInput: function(e) {
    const postIndex = e.currentTarget.dataset.postIndex;
    this.setData({ [`commentInputs.${postIndex}`]: e.detail.value });
  },

  showReplyInput: function(e) {
    const commentId = e.currentTarget.dataset.commentId;
    this.setData({ replyTo: { commentId, userName: '' }, replyToPostIndex: null });
  },

  handleReplyInput: function(e) {
    const commentId = e.currentTarget.dataset.commentId;
    this.setData({ [`replyInputs.${commentId}`]: e.detail.value });
  },

  submitReply: function(e) {
    const postIndex = e.currentTarget.dataset.postIndex;
    const commentId = e.currentTarget.dataset.commentId;
    const replyContent = this.data.replyInputs[commentId] || '';
    if (!replyContent.trim()) return;
    const userInfo = wx.getStorageSync('userInfo') || { avatar: '', name: '' };
    const posts = this.data.posts.slice();
    const post = posts[postIndex];
    const comment = post.comments.find(c => c.id === commentId);
    if (comment && !comment.reply) {
      comment.reply = {
        user: userInfo.name,
        avatar: userInfo.avatar,
        content: replyContent,
        time: new Date().toLocaleString()
      };
      this.setData({
        posts,
        [`replyInputs.${commentId}`]: '',
        replyTo: null,
        replyToPostIndex: null
      });
      wx.setStorageSync('posts', posts);
    }
  },

  deleteComment: function(e) {
    const postIndex = e.currentTarget.dataset.postIndex;
    const commentId = e.currentTarget.dataset.commentId;
    const posts = this.data.posts.slice();
    const post = posts[postIndex];
    const userInfo = wx.getStorageSync('userInfo') || { name: '' };
    // 判断权限：发帖人或评论人
    const commentIndex = post.comments.findIndex(c => c.id === commentId);
    if (commentIndex !== -1) {
      const comment = post.comments[commentIndex];
      if (userInfo.name === post.user || userInfo.name === comment.user) {
        post.comments.splice(commentIndex, 1);
        this.setData({ posts });
        wx.setStorageSync('posts', posts);
      }
    }
  },

  deleteReply: function(e) {
    const postIndex = e.currentTarget.dataset.postIndex;
    const commentId = e.currentTarget.dataset.commentId;
    const posts = this.data.posts.slice();
    const post = posts[postIndex];
    const userInfo = wx.getStorageSync('userInfo') || { name: '' };
    const comment = post.comments.find(c => c.id === commentId);
    // 只有发帖人或回复人可以删除
    if (comment && comment.reply && (userInfo.name === post.user || userInfo.name === comment.reply.user)) {
      comment.reply = null;
      this.setData({ posts });
      wx.setStorageSync('posts', posts);
    }
  },

  onCommentLongPress: function(e) {
    const postIndex = e.currentTarget.dataset.postIndex;
    const commentId = e.currentTarget.dataset.commentId;
    const posts = this.data.posts.slice();
    const post = posts[postIndex];
    const commentIndex = post.comments.findIndex(c => c.id === commentId);
    if (commentIndex === -1) return;
    // 仅允许评论本人删除，去除前后空格并转为字符串后比较
    const userInfo = wx.getStorageSync('userInfo') || { name: '' };
    const commentUser = String(post.comments[commentIndex].user || '').trim();
    const currentUser = String(userInfo.name || '').trim();
    console.log('评论用户:', commentUser, '当前用户:', currentUser); // 调试输出
    if (commentUser !== currentUser) {
      wx.showToast({ title: '只能删除自己的评论', icon: 'none' });
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确定要删除这条评论吗？',
      success: (res) => {
        if (res.confirm) {
          post.comments.splice(commentIndex, 1);
          this.setData({ posts });
          wx.setStorageSync('posts', posts);
        }
      }
    });
  },

  onReplyComment: function(e) {
    const userInfo = wx.getStorageSync('userInfo') || { name: '' };
    if (!userInfo.name) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    const commentId = e.currentTarget.dataset.commentId;
    const postIndex = e.currentTarget.dataset.postIndex;
    const posts = this.data.posts;
    const post = posts[postIndex];
    const comment = post.comments.find(c => c.id === commentId);
    if (comment.user === userInfo.name) {
      wx.showToast({ title: '不能回复自己', icon: 'none' });
      return;
    }
    this.setData({ replyTo: { commentId, userName: comment.user }, replyToPostIndex: postIndex });
  },

  cancelReply: function() {
    this.setData({ replyTo: null, replyToPostIndex: null });
  },

  onReplyLongPress: function(e) {
    const postIndex = e.currentTarget.dataset.postIndex;
    const commentId = e.currentTarget.dataset.commentId;
    const replyIndex = e.currentTarget.dataset.replyIndex;
    const posts = this.data.posts.slice();
    const post = posts[postIndex];
    const comment = post.comments.find(c => c.id === commentId);
    const userInfo = wx.getStorageSync('userInfo') || { name: '' };
    if (comment && comment.replies && comment.replies[replyIndex].user === userInfo.name) {
      wx.showModal({
        title: '提示',
        content: '确定要删除这条回复吗？',
        success: (res) => {
          if (res.confirm) {
            comment.replies.splice(replyIndex, 1);
            this.setData({ posts });
            wx.setStorageSync('posts', posts);
          }
        }
      });
    } else {
      wx.showToast({ title: '只能删除自己的回复', icon: 'none' });
    }
  },
})